#ifndef _breg_
#define _breg_
#include <string>
#include <oniguruma.h>
#include <vector>


#if defined(__BORLANDC__)
#pragma comment(lib, "onig_bcc.lib")
#endif

#if defined(_MSC_VER)
#pragma comment(lib, "onig.lib")
#endif



class adrsize { 
public: char *adress; unsigned int size; 
adrsize () : adress(NULL), size(0) {}
adrsize (char *p, unsigned int s) : adress(p), size(s) {}
std::string str() {  return std::string(adress, size); } };


std::vector<adrsize> RegExp;
int Bfind( const char *start,const char *end, std::string ptn ) {
RegExp.resize(0);
int r; regex_t* reg; OnigErrorInfo einfo;
r = onig_new(&reg, (UChar*)&ptn[0], (UChar*)&ptn[ptn.size()] ,ONIG_OPTION_DEFAULT|ONIG_OPTION_MULTILINE|ONIG_OPTION_CAPTURE_GROUP, ONIG_ENCODING_ASCII, ONIG_SYNTAX_DEFAULT , &einfo);
if (r != ONIG_NORMAL) return NULL;
OnigRegion *region = onig_region_new();
r = onig_search(reg, (UChar*)start, (UChar*)end, (UChar*)start, (UChar*)end, region, ONIG_OPTION_NONE);
if (r < 0) {  onig_region_free(region, 1 ); onig_free(reg); onig_end();  return 0; }
int n=region->num_regs;
RegExp.reserve(n);
unsigned int size; 
for( r=0; r < n; r++ ) {
size = (unsigned int) (region->end[r]-region->beg[r]);
RegExp.push_back( adrsize( (char*)(start + region->beg[r]), size  )  );  
}
onig_region_free(region, 1 ); onig_free(reg); onig_end(); 
return RegExp.size(); }
//
int Bfind(const std::string &s, std::string ptn ) {  
int n=s.size()-1;
if(n<1) return 0;
return Bfind( &s[0], &s[ n ] , ptn ); }



void BReplace( std::string &src, std::string from, std::string to){
int n, k , l; char *p=&src[0], *q;  
std::string s; s.reserve(src.size()); s="";
while(1) {
n = Bfind( p,  &src[src.size()], from );
if(n==0) break; 
q=RegExp[0].adress;
n=RegExp[0].size;
k = (unsigned int)p-(unsigned int)&src[0];  
l = (unsigned int)q-(unsigned int)&src[0];  
s += src.substr(k,  l-k ); s += to;
p = q + n;
if((unsigned int)p >= (unsigned int)&src[0]+src.size() ) break; 
}
k = (unsigned int)p-(unsigned int)&src[0];  
src = s + src.substr(k, src.size()-k);  
}




/*


void BReplace( std::string &src, std::string from, std::string to){
int n, k , l; char *p=&src[0], *q;  
std::string s; s.reserve(src.size()); s="";
while(1) {
q = Bfind( p,  &src[src.size()], from, &n);
if(q==NULL) break; 
k = (unsigned int)p-(unsigned int)&src[0];  
l = (unsigned int)q-(unsigned int)&src[0]; 
s += src.substr(k, l-k); s += to;
p = q + n;
if((unsigned int)p >= (unsigned int)&src[0]+src.size() ) break; 
}
k = (unsigned int)p-(unsigned int)&src[0];  
src = s + src.substr(k, src.size()-k);  
}
*/

#endif